package com.franferri;

import java.io.StringReader;

public class ExampleJavaHtml2Text {

	public static void main(String[] args) {

		String html_input = "<body>A&ntilde;adir</body>";

		System.out.println("Input:" + html_input);

		System.out.println("Manual: before=" + html_input + ", after=" + doManual(html_input));

		System.out.println("Automatic: before=" + html_input + ", after=" + doAutomatic(html_input));

	}

	private static String doManual(String html_input) {

		// We create a new string to save the modifications, although is not necessary because html_input is passed by value, not by reference
		String tmp_text = "";

		// We remove all html tags like "<tags>" inside the html_input string
		tmp_text = html_input.replaceAll("\\<.*?\\>", "");

		// We remove the desired html ascii codes "&oacute;" inside the html_input string, but this is encoding dependent
		// Take a look to http://www.ascii.cl/htmlcodes.htm, and you can see that the list is dependent of the encoding
		// Most of them have 2 valid codes:
		// html code (like "&#34;")
		// html name (like "&quot;")
		// for the double quote '"'
		tmp_text = tmp_text.replaceAll("&ntilde;", "ñ");
		tmp_text = tmp_text.replaceAll("&#241;", "ñ");

		return tmp_text;

	}

	private static String doAutomatic(String html_input) {

		Html2Text parser = new Html2Text();

		try {

			parser.parse(new StringReader(html_input));

		} catch (Exception e) {
			e.printStackTrace();
		}

		return parser.getText();

	}

}
